<template>
	<div id="user-profile-view">
		<div class="profile-container">
			<a-card title="个人信息" :loading="loading">
				<a-form
					:model="userForm"
					name="userProfile"
					:label-col="{ span: 6 }"
					:wrapper-col="{ span: 18 }"
					@finish="handleUpdateProfile"
				>
					<a-form-item label="用户头像">
						<div class="avatar-upload">
							<div class="avatar-container">
								<a-avatar v-if="userForm.userAvatar" :src="userForm.userAvatar" :size="80" />
								<a-avatar v-else :size="80" style="background-color: #87d068">
									{{ userForm.userName?.[0]?.toUpperCase() }}
								</a-avatar>
								<div v-if="avatarUploading" class="avatar-loading">
									<a-spin size="small" />
								</div>
							</div>
							<div class="avatar-actions">
								<a-tabs v-model:active-key="avatarUploadMode" type="card" size="small">
									<a-tab-pane key="file" tab="本地上传">
										<a-upload
											:show-upload-list="false"
											:before-upload="beforeUpload"
											:custom-request="handleAvatarUpload"
											class="avatar-uploader"
											accept="image/jpeg,image/jpg,image/png"
										>
											<a-button size="small" :loading="avatarUploading">
												<UploadOutlined />
												{{ avatarUploading ? '上传中...' : '上传头像' }}
											</a-button>
										</a-upload>
									</a-tab-pane>
									<a-tab-pane key="url" tab="URL上传">
										<UrlPictureUpload
											:picture="userForm.userAvatar ? { url: userForm.userAvatar } : undefined"
											:onSuccess="handleUrlUploadSuccess"
										/>
									</a-tab-pane>
								</a-tabs>
							</div>
						</div>
						<div class="avatar-tips">
							<a-typography-text type="secondary" style="font-size: 12px">
								支持 JPG、PNG 格式，文件大小不超过 2MB
							</a-typography-text>
						</div>
					</a-form-item>

					<a-form-item label="用户名" name="userName" :rules="[{ required: true, message: '请输入用户名!' }]">
						<a-input v-model:value="userForm.userName" placeholder="请输入用户名" />
					</a-form-item>

					<a-form-item label="用户账号">
						<a-input v-model:value="userForm.userAccount" disabled />
					</a-form-item>

					<a-form-item label="用户角色">
						<div style="display: flex; align-items: center">
							<a-tag :color="getRoleColor(userForm.userRole)">
								{{ getRoleText(userForm.userRole) }}
							</a-tag>
							<SimpleVipBadge :vip-expire-time="userForm.vipExpireTime" :user-role="userForm.userRole" />
						</div>
					</a-form-item>

					<a-form-item label="用户简介" name="userProfile">
						<a-textarea
							v-model:value="userForm.userProfile"
							placeholder="请输入个人简介"
							:rows="4"
							:max-length="200"
							show-count
						/>
					</a-form-item>

					<a-form-item label="注册时间">
						<span>{{ formatTime(userForm.createTime) }}</span>
					</a-form-item>

					<a-form-item :wrapper-col="{ offset: 6, span: 18 }">
						<a-space>
							<a-button type="primary" html-type="submit" :loading="updating"> 保存修改 </a-button>
							<a-button @click="resetForm"> 重置 </a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</a-card>

			<!-- 修改密码卡片 -->
			<a-card title="修改密码" style="margin-top: 24px">
				<a-alert
					message="安全提示"
					description="为了您的账户安全，请设置密码长度为8-20位。新密码不能与当前密码相同。"
					type="info"
					show-icon
					style="margin-bottom: 24px"
				/>
				<a-form
					:model="passwordForm"
					name="passwordForm"
					:label-col="{ span: 6 }"
					:wrapper-col="{ span: 18 }"
					@finish="handleUpdatePassword"
				>
					<a-form-item label="当前密码" name="oldPassword" :rules="[{ required: true, message: '请输入当前密码!' }]">
						<a-input-password
							v-model:value="passwordForm.oldPassword"
							placeholder="请输入当前密码"
							autocomplete="current-password"
						/>
					</a-form-item>

					<a-form-item
						label="新密码"
						name="newPassword"
						:rules="[
							{ required: true, message: '请输入新密码!' },
							{ min: 8, message: '密码长度不能少于8位!' },
							{ max: 20, message: '密码长度不能超过20位!' },
							{ validator: validatePasswordStrength },
						]"
					>
						<a-input-password
							v-model:value="passwordForm.newPassword"
							placeholder="请输入新密码（8-20位）"
							autocomplete="new-password"
						/>
					</a-form-item>

					<a-form-item
						label="确认新密码"
						name="confirmPassword"
						:rules="[{ required: true, message: '请确认新密码!' }, { validator: validateConfirmPassword }]"
					>
						<a-input-password
							v-model:value="passwordForm.confirmPassword"
							placeholder="请再次输入新密码"
							autocomplete="new-password"
						/>
					</a-form-item>

					<a-form-item :wrapper-col="{ offset: 6, span: 18 }">
						<a-space>
							<a-button type="primary" html-type="submit" :loading="passwordUpdating"> 修改密码 </a-button>
							<a-button @click="resetPasswordForm"> 重置 </a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</a-card>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { getLoginUserUsingGet, updateUserUsingPost, updateUserPasswordUsingPost } from '@/api/userController'
import { uploadPictureUsingPost } from '@/api/pictureController'
import ACCESS_ENUM from '@/access/accessEnum'
import dayjs from 'dayjs'
import UrlPictureUpload from '@/components/picture/UrlPictureUpload.vue'
import SimpleVipBadge from '@/components/SimpleVipBadge.vue'

const loginUserStore = useLoginUserStore()
const loading = ref(false)
const updating = ref(false)
const passwordUpdating = ref(false)
const avatarUploading = ref(false)
const avatarUploadMode = ref('file') // 头像上传模式：file 或 url

// 用户表单数据
const userForm = reactive<{
	id?: number
	userName?: string
	userAccount?: string
	userAvatar?: string
	userProfile?: string
	userRole?: string
	createTime?: string
	vipExpireTime?: string
}>({})

// 密码表单数据
const passwordForm = reactive<{
	oldPassword?: string
	newPassword?: string
	confirmPassword?: string
}>({
	oldPassword: '',
	newPassword: '',
	confirmPassword: '',
})

// 获取角色颜色
const getRoleColor = (role?: string) => {
	const colorMap: Record<string, string> = {
		[ACCESS_ENUM.NOT_LOGIN]: 'default',
		[ACCESS_ENUM.USER]: 'blue',
		vip: 'gold',
		[ACCESS_ENUM.ADMIN]: 'red',
	}
	return colorMap[role || ACCESS_ENUM.NOT_LOGIN]
}

// 获取角色文本
const getRoleText = (role?: string) => {
	const textMap: Record<string, string> = {
		[ACCESS_ENUM.NOT_LOGIN]: '未登录',
		[ACCESS_ENUM.USER]: '普通用户',
		vip: 'VIP用户',
		[ACCESS_ENUM.ADMIN]: '管理员',
	}
	return textMap[role || ACCESS_ENUM.NOT_LOGIN]
}

// 格式化时间
const formatTime = (time?: string) => {
	return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取用户信息
const fetchUserProfile = async () => {
	loading.value = true
	try {
		const res = await getLoginUserUsingGet()
		if (res.data.code === 0 && res.data.data) {
			Object.assign(userForm, res.data.data)
		}
	} catch (error) {
		message.error('获取用户信息失败')
	} finally {
		loading.value = false
	}
}

// 更新用户信息
const handleUpdateProfile = async () => {
	updating.value = true
	try {
		const res = await updateUserUsingPost({
			id: userForm.id,
			userName: userForm.userName,
			userAvatar: userForm.userAvatar,
			userProfile: userForm.userProfile,
		})
		if (res.data.code === 0) {
			message.success('更新成功')
			// 更新全局用户信息
			await loginUserStore.fetchLoginUser()
		} else {
			message.error(res.data.message || '更新失败')
		}
	} catch (error) {
		message.error('更新失败')
	} finally {
		updating.value = false
	}
}

// 重置表单
const resetForm = () => {
	fetchUserProfile()
}

// 头像上传前检查
const beforeUpload = (file: File) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
	if (!isJpgOrPng) {
		message.error('只能上传 JPG/PNG 格式的图片!')
		return false
	}
	const isLt2M = file.size / 1024 / 1024 < 2
	if (!isLt2M) {
		message.error('图片大小不能超过 2MB!')
		return false
	}
	return true
}

// 处理头像上传
const handleAvatarUpload = async ({ file }: any) => {
	avatarUploading.value = true
	try {
		// 使用图片上传接口上传头像
		const res = await uploadPictureUsingPost({}, {}, file)
		const responseData = res.data as API.BaseResponsePictureVO_
		if (responseData.code === 0 && responseData.data) {
			// 上传成功，更新用户头像
			userForm.userAvatar = responseData.data.url
			message.success('头像上传成功！请点击"保存修改"按钮完成更新')
		} else {
			message.error('头像上传失败：' + responseData.message)
		}
	} catch (error: any) {
		console.error('头像上传失败', error)
		message.error('头像上传失败：' + error.message)
	} finally {
		avatarUploading.value = false
	}
}

// 处理URL上传成功
const handleUrlUploadSuccess = (picture: API.PictureVO) => {
	userForm.userAvatar = picture.url
	message.success('头像上传成功！请点击"保存修改"按钮完成更新')
}

// 验证确认密码
const validateConfirmPassword = async (_rule: any, value: string) => {
	if (value && value !== passwordForm.newPassword) {
		return Promise.reject(new Error('两次输入的密码不一致！'))
	}
	return Promise.resolve()
}

// 验证新密码强度
const validatePasswordStrength = async (_rule: any, value: string) => {
	if (!value) {
		return Promise.resolve()
	}

	// 检查是否与当前密码相同
	if (value === passwordForm.oldPassword) {
		return Promise.reject(new Error('新密码不能与当前密码相同！'))
	}

	return Promise.resolve()
}

// 重置密码表单
const resetPasswordForm = () => {
	passwordForm.oldPassword = ''
	passwordForm.newPassword = ''
	passwordForm.confirmPassword = ''
}

// 处理修改密码
const handleUpdatePassword = async () => {
	passwordUpdating.value = true
	try {
		const res = await updateUserPasswordUsingPost({
			oldPassword: passwordForm.oldPassword,
			newPassword: passwordForm.newPassword,
		})

		if (res.data.code === 0) {
			message.success('密码修改成功！为了账户安全，建议您重新登录')
			resetPasswordForm()

			setTimeout(() => {
				loginUserStore.setLoginUser({})
				window.location.href = '/user/login'
			}, 2000)
		} else {
			message.error(res.data.message || '密码修改失败')
		}
	} catch (error: any) {
		console.error('密码修改失败', error)
		// 根据错误信息给出更友好的提示
		if (error.response?.status === 400) {
			message.error('当前密码输入错误，请检查后重试')
		} else {
			message.error('密码修改失败，请重试')
		}
	} finally {
		passwordUpdating.value = false
	}
}

onMounted(() => {
	fetchUserProfile()
})
</script>

<style scoped lang="scss">
#user-profile-view {
	max-width: 800px;
	margin: 0 auto;
	padding: 24px;

	.profile-container {
		.avatar-upload {
			display: flex;
			align-items: center;
			margin-bottom: 8px;

			.avatar-container {
				position: relative;
				display: inline-block;

				.avatar-loading {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: rgba(255, 255, 255, 0.8);
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 50%;
				}
			}
		}

		.avatar-tips {
			margin-top: 4px;
		}

		// 修改密码卡片样式
		.ant-card:last-child {
			border: 1px solid #f0f0f0;

			:deep(.ant-card-head) {
				background: #fafafa;

				.ant-card-head-title {
					color: #595959;
					font-weight: 500;
				}
			}
		}
	}
}
</style>
